<template>
  <div class="role-list-container">
    <!-- 操作按钮区域 -->
    <div class="action-bar">
      <div class="left-actions">
        <el-button type="primary" icon="el-icon-plus" @click="handleAddRole">添加角色</el-button>
        <el-button type="info" icon="el-icon-refresh" @click="fetchRoleList">刷新</el-button>
      </div>
      <div class="right-actions">
        <el-input
          v-model="searchQuery"
          placeholder="搜索角色名称"
          prefix-icon="el-icon-search"
          clearable
          class="search-input"
          @clear="handleSearch"
          @keyup.enter.native="handleSearch"
        >
          <el-button slot="append" icon="el-icon-search" @click="handleSearch"></el-button>
        </el-input>
      </div>
    </div>

    <!-- 角色列表表格 -->
    <el-card shadow="hover" class="table-card">
      <el-table
        :data="roleList"
        border
        stripe
        style="width: 100%"
        v-loading="loading"
        @selection-change="handleSelectionChange"
        class="role-table"
        :show-header="true"
        :default-sort="{ prop: 'roleId', order: 'ascending' }"
        :header-cell-style="{ backgroundColor: '#f5f7fa', color: '#606266' }"
      >
        <el-table-column prop="roleId" label="角色ID" width="300" align="center"></el-table-column>
        <el-table-column prop="roleName" label="角色名称" width="300" align="center"></el-table-column>
        <el-table-column prop="roleDescription" label="描述" width="520" align="center"></el-table-column>
        
        <el-table-column label="操作" width="400" align="center">
          <template slot-scope="scope">
            <el-tooltip content="编辑" placement="top">
              <el-button type="primary" size="mini" icon="el-icon-edit" @click="handleEditRole(scope.row)"></el-button>
            </el-tooltip>
            <el-tooltip content="删除" placement="top">
              <el-button type="danger" size="mini" icon="el-icon-delete" @click="handleDeleteRole(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>
    </el-card>

    <!-- 分页控件 -->
    <div class="pagination-container">
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="pagination.currentPage"
        :page-sizes="[10, 20, 50, 100]"
        :page-size="pagination.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="pagination.total"
        background
      ></el-pagination>
    </div>

    <!-- 添加/编辑角色对话框 -->
    <el-dialog :title="dialogTitle" :visible.sync="dialogVisible" width="500px" @close="resetForm">
      <el-form :model="roleForm" :rules="rules" ref="roleForm" label-width="100px">
        <el-form-item label="角色名称" prop="roleName">
          <el-input v-model="roleForm.roleName" placeholder="请输入角色名称" class="unified-input"></el-input>
        </el-form-item>
        <el-form-item label="描述" prop="roleDescription">
          <el-input v-model="roleForm.roleDescription" placeholder="请输入角色描述" class="unified-input"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="dialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitForm">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import service from '@/utils/request';
export default {
  name: 'RoleList',
  data() {
    return {
      roleList: [],
      loading: false,
      searchQuery: '',
      pagination: {
        currentPage: 1,
        pageSize: 10,
        total: 0
      },
      selectedRoles: [],
      dialogVisible: false,
      dialogTitle: '添加角色',
      isAddMode: true,
      roleForm: {
        roleId: '',
        roleName: '',
        roleDescription: '',
        token: localStorage.getItem('token')
      },
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' }
        ],
        description: [
          { required: true, message: '请输入角色描述', trigger: 'blur' }
        ]
      }
    };
  },
  created() {
    this.fetchRoleList();
  },
  methods: {
    fetchRoleList() {
      this.loading = true;
      service.get('/api/system/role/getRoleList', {
        params: {
          pageNum: this.pagination.currentPage,
          pageSize: this.pagination.pageSize,
          roleName: this.searchQuery
        }
      }).then(res => {
        if (res.code === 200) {
          this.roleList = res.data.list;
          this.pagination.total = res.data.total;
        } else {
          this.$message.error('获取角色列表失败');
        }
      }).catch(err => {
        this.$message.error(err.message);
      }).finally(() => {
        this.loading = false;
      });
    },
    
    handleSearch() {
      this.pagination.currentPage = 1;
      this.fetchRoleList();
    },
    
    handleAddRole() {
      this.dialogTitle = '添加角色';
      this.isAddMode = true;
      this.resetForm();
      this.dialogVisible = true;
    },
    
    handleEditRole(row) {
      this.dialogTitle = '编辑角色';
      this.isAddMode = false;
      this.roleForm = { ...row };
      this.dialogVisible = true;
    },
    
    handleDeleteRole(row) {
      this.$confirm('此操作将永久删除该角色, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        service.delete(`/api/system/role/deleteRole/${row.roleId}`).then(res => {
          if (res.code === 200) {
            this.$message({
              type: 'success',
              message: '删除成功!'
            });
            this.fetchRoleList();
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });
      });
    },
    
    handleSizeChange(val) {
      this.pagination.pageSize = val;
      this.fetchRoleList();
    },
    
    handleCurrentChange(val) {
      this.pagination.currentPage = val;
      this.fetchRoleList();
    },
    
    submitForm() {
      this.$refs.roleForm.validate((valid) => {
        if (valid) {
          const apiUrl = this.isAddMode ? '/api/system/role/addRole' : '/api/system/role/updateRole';
          this.roleForm.token=localStorage.getItem('token');
          const request=this.isAddMode?service.post(apiUrl, this.roleForm):service.put(apiUrl, this.roleForm);
          request.then(res => {
            if (res.code === 200) {
              this.$message({
                type: 'success',
                message: this.isAddMode ? '添加角色成功!' : '更新角色成功!'
              });
              this.dialogVisible = false;
              this.fetchRoleList(); // 刷新角色列表
            } 
          }).catch(err => {
            this.$message.error(err.message);
          });
        }
      });
    },
    
    resetForm() {
      if (this.$refs.roleForm) {
        this.$refs.roleForm.resetFields();
      }
      this.roleForm = {
        roleId: '',
        roleName: '',
        roleDescription: '',
        token: localStorage.getItem('token')
      };
    }
  }
};
</script>

<style scoped>
.role-list-container {
  padding: 20px;
}

.action-bar {
  margin-bottom: 20px;
  display: flex;
  justify-content: space-between;
}

.search-input {
  width: 250px;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end; /* 右对齐 */
}

.table-card {
  margin-bottom: 20px; /* 卡片底部间距 */
}

/* Element UI 默认样式覆盖 */
.role-table th {
  background-color: #f5f7fa; /* 表头背景颜色 */
  color: #606266; /* 表头字体颜色 */
}

.role-table tr:hover {
  background-color: #f5f7fa; /* 行悬停背景颜色 */
}
</style>
